/**
 * 
 */
package org.vectrics.recruiter.struts.admin.employee;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.vectrics.common.util.DateUtil;
import org.vectrics.employee.Employee;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.struts.employee.EmployeeForm;
import org.vectrics.struts.VectricsActionData;

import com.hexacta.hrs.services.employee.impl.EmploymentConditionDTO;

/**
 * Clase encargada de llenar Formulario de Empleado
 * 
 * @author pgoette
 * 
 */
public class FillerEmployeeForm {

    public void fillEmployeeForm(VectricsActionData actionData, String idPerson, String idCompany, String effectiveDate) {
        // Si no son nulos
        if ((idPerson != null) && (idCompany != null)) {
            // Busco el empleado
            Employee employee = RecruitServiceLocator.getCompanyService().findEmployee(new Long(idPerson),
                    new Long(idCompany));
            // Busco el formulario
            EmployeeForm employeeForm = (EmployeeForm) actionData.getForm();
            if (employeeForm == null) {
                employeeForm = new EmployeeForm();
                actionData.saveForm(employeeForm);
            }

            EmploymentConditionDTO employmentConditionDTO = null;
            Set<EmploymentConditionDTO> employmentConditions = CoreServiceLocator.getEmployeeService()
                    .getEmploymentConditionHistory(employee);

            // Seteo los datos al formulario del empleado
            employeeForm.setDate(DateUtil.getFechaFormateada(employee.getFirstEmployeeDate()));
            employeeForm.setDateStart(DateUtil.getFechaFormateada(employee.getDateStart()));
            employeeForm.setId(employee.getId().toString());
            employeeForm.setElegibleMentor(employee.isElegibleMentor());
            employeeForm.setElegibleProjectMember(employee.isElegibleProjectMember());

            // Seteo los datos del historial
            if (employmentConditions != null) {

                if (effectiveDate == null) {
                    employmentConditionDTO = getCurrentCondition(employmentConditions);
                    if (employmentConditionDTO != null) {
                        employeeForm.setRecordEffectiveDay(DateUtil.getFechaFormateada(employmentConditionDTO
                                .getEffectiveDate()));
                    }
                } else {
                    Date date = DateUtil.getDateByTime(effectiveDate);
                    employmentConditionDTO = getCondition(employmentConditions, date);
                    employeeForm.setRecordEffectiveDay(DateUtil.getFechaFormateada(date));
                }

                // if (employee.getJob().getJobTerm().getIsEmployee()){
                //employeeForm.setDateStartAsEmployee(DateUtil.getFechaFormateada
                // (
                // employee.getFirstEmployeeDay()));
                // }

                employeeForm.setDateEnd(DateUtil.getFechaFormateada(employee.getDateEnd()));

                if (employmentConditionDTO.getCareerRole() != null) {
                    employeeForm.setFunction(employmentConditionDTO.getCareerRole().getCareerRole().getCode());
                    // Seteo el function code como atributo de la request
                    // para utilizar el componente
                    actionData.getRequest().setAttribute("function",
                            employmentConditionDTO.getCareerRole().getCareerRole().getCode());
                }
                actionData.getRequest().setAttribute("medicalInsurance", employee.getMedicalInsurance());
                
                // Si la office location del empleado es distinta de null se la
                // seteo al formulario.
                if ((employmentConditionDTO.getAgreementContidion()!=null) && (employmentConditionDTO.getAgreementContidion().getLocation() != null)) {
                    employeeForm.setLocation(employmentConditionDTO.getAgreementContidion().getLocation().getId()
                            .toString());
                    actionData.getRequest().setAttribute("location",
                            employmentConditionDTO.getAgreementContidion().getLocation().getId().toString());
                } else {
                	if (employee.getLocation()!=null) {
                		employeeForm.setLocation(employee.getLocation().getId()
                                .toString());
                        actionData.getRequest().setAttribute("location",
                        		employee.getLocation().getId().toString());
                	}
                }

                if (employmentConditionDTO.getCareerRole() != null) {
                	employeeForm.setCareerRolePosition(employmentConditionDTO.getCareerRole().getCareerRolePosition()
                			.toString());                	
                } else {
                	employeeForm.setCareerRolePosition(employee.getCareerRolePosition().toString());
                }

                // Set the mentor if the employee has one
                if (employmentConditionDTO.getMentorAssignment() != null && employmentConditionDTO.getMentorAssignment().getMentor() != null) {
                    employeeForm.setIdMentor(employmentConditionDTO.getMentorAssignment().getMentor().getPerson()
                            .getId().toString());
                    actionData.getRequest().setAttribute("idMentor",
                            employmentConditionDTO.getMentorAssignment().getMentor().getPerson().getId().toString());
                }
                
                // Set the career role position and hours per day
                if (employmentConditionDTO.getAgreementContidion()==null) {
                	 employeeForm.setHoursPerDay(employee.getHoursPerDay().toString());
                	 if (employee.getMedicalInsurance() != null) {
                         employeeForm.setMedicalInsurance(employee.getMedicalInsurance());
                     }
                } else {
                	 employeeForm.setHoursPerDay(employmentConditionDTO.getAgreementContidion().getHoursPerDay().toString());
                	 employeeForm.setMedicalInsurance(employmentConditionDTO.getAgreementContidion()
                             .getMedicalInsurance());
                }
                
                if (employee.getLastAgreementDay() != null) {
                    employeeForm.setLastAgreementDay(DateUtil.getFechaFormateada(employee.getLastAgreementDay()));
                }
            }

        }
    }

    private EmploymentConditionDTO getCondition(Set<EmploymentConditionDTO> employmentConditions, final Date date) {
        Set<EmploymentConditionDTO> employmentConditionDTOs = new HashSet<EmploymentConditionDTO>(employmentConditions);

        if (employmentConditionDTOs.isEmpty()) {
            return null;
        }

        CollectionUtils.filter(employmentConditionDTOs, new Predicate() {

            @Override
            public boolean evaluate(Object object) {
                EmploymentConditionDTO careerRole = (EmploymentConditionDTO) object;
                return new Long(careerRole.getEffectiveDate().getTime()).equals(date.getTime());
            }

        });

        if (employmentConditionDTOs.isEmpty()) {
            return null;
        }

        return employmentConditionDTOs.iterator().next();
    }

    private EmploymentConditionDTO getCurrentCondition(Set<EmploymentConditionDTO> employmentConditions) {

        if (employmentConditions.isEmpty()) {
            return null;
        }

        EmploymentConditionDTO employmentConditionDTO = (EmploymentConditionDTO) Collections.max(employmentConditions,
                new Comparator<EmploymentConditionDTO>() {
                    @Override
                    public int compare(EmploymentConditionDTO o1, EmploymentConditionDTO o2) {
                        if (o1.getEffectiveDate() != null && o2.getEffectiveDate() != null) {
                            return o1.getEffectiveDate().compareTo(o2.getEffectiveDate());
                        } else {
                            return 0;
                        }
                    }

                });
        return employmentConditionDTO;
    }

}
